import axios from 'axios'

const api = axios.create({
  baseURL: 'http://localhost:8000/',
  timeout: 120000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response) {
      // 处理错误响应
      switch (error.response.status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          localStorage.removeItem('token')
          window.location.href = '/login'
          break
        default:
          console.error('API请求错误:', error.response.data)
      }
    }
    return Promise.reject(error)
  }
)

// 获取算法列表
export const getAlgorithms = () => {
  return api.get('/detection/algorithms')
}

// 获取单个算法详情
export const getAlgorithm = (algorithmId) => {
  return api.get(`/detection/algorithms/${algorithmId}`)
}

// 上传数据集
export const uploadDataset = (formData) => {
  return api.post('/detection/datasets/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 获取数据集列表
export const getDatasets = (skip = 0, limit = 100) => {
  return api.get(`/detection/datasets?skip=${skip}&limit=${limit}`)
}

// 获取单个数据集详情
export const getDataset = (datasetId) => {
  return api.get(`/detection/datasets/${datasetId}`)
}

// 创建检测任务
export const createTask = (taskData) => {
  return api.post('/detection/tasks', taskData)
}

// 获取任务列表
export const getTasks = (skip = 0, limit = 100) => {
  return api.get(`/detection/tasks?skip=${skip}&limit=${limit}`)
}

// 获取单个任务详情
export const getTaskDetail = (taskId) => {
  return api.get(`/detection/tasks/${taskId}`)
}

// 开始执行任务
export const startTask = (taskId) => {
  return api.post(`/detection/tasks/${taskId}/start`)
}

// 获取任务统计数据
export const getTaskStatistics = (taskId) => {
  return api.get(`/detection/tasks/${taskId}/statistics`)
}

// 获取可用模型列表
export const getAvailableModels = () => {
  return api.get('/detection/models')
}

// 执行模型预测
export const runModelPrediction = (modelType, file) => {
  const formData = new FormData()
  formData.append('model_type', modelType)
  formData.append('file', file)
  
  return api.post('/detection/run_model', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 获取最新预测结果
export const getLatestResult = () => {
  return api.get('/detection/latest_result')
}

// 获取预测日志列表
export const getPredictionLogs = (skip = 0, limit = 20) => {
  return api.get(`/detection/prediction_logs?skip=${skip}&limit=${limit}`)
}

// 获取单个预测日志详情
export const getPredictionLogDetail = (logId) => {
  return api.get(`/detection/prediction_logs/${logId}`)
}